import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: process.env['VUE_APP_BASE_API'],
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(

  (response) => {
    const { data, message, success } = response.data
    if (response.data instanceof Blob) return response.data
    if (success) {
      return data
    }
    Message.error(message)
    return Promise.reject(response)
  },
  (error) => {
    console.dir(error)
    if (error.response.status === 401) {
      store.dispatch('user/logOut')
      router.push('/login')
    }
    Message.error(error.response?.data?.message) || '系统出错，请联系管理员~'
    return Promise.reject(error)
  }
)

export default request
